<template>
	<view class="nickname-container">
		<uni-forms ref="nickNameForm" :model="formData">
			<uni-forms-item name="nickname"
				:rules="[{required:true,errorMessage:'用户名不能为空',validateFunction:validateFn}]">
				<uni-easyinput v-model="formData.nickname" />
				<text style="color:#909090">输入1-8个文字和英文数字的组合</text>
			</uni-forms-item>
		</uni-forms>
		<button @click="submit" type="default" hover-class="active">确定</button>
	</view>
</template>

<script setup>
	import { ref } from "vue"
	import { updateUserApi } from "@/api/users.js"
	import useUser from "@/store/users.js"
	//store
	let userStore = useUser();

	// 表单的数据对象
	let formData = ref({
		nickname: userStore.userInfo.nickname
	})
	//表单组件的引用对象
	let nickNameForm = ref(null);
	//提交表单
	let submit = () => {
		nickNameForm.value.validate(async (err, value) => {
			if (!err) {
				//打开加载动画
				uni.showToast({
					title: '正在修改',
					icon: "loading",
					duration:1000*10
				})
				try {
					let res = await updateUserApi({
						unid: userStore.userInfo.unid,
						nickname: formData.value.nickname
					})
					// console.log(res)
					//更改本地store中的nickname
					userStore.userInfo.nickname = formData.value.nickname;
					//重新跳转到个人中心页面
					uni.navigateBack()
					//关闭加载动画
					uni.hideToast()
				} catch (e) {
					console.log('error---', e.toString())
				}
			}
		})
	}
	//表单校验的验证函数
	let validateFn = (rule, value, data, callback) => {
		if (value.length < 0 || value.length > 8) {
			callback('用户名长度1-8位')
		}
	}
</script>

<style lang="scss">
	.nickname-container {
		background-color: #f4f4f4;
		min-height: 100vh;
		padding: 20px 15px 0;

		:deep(.uni-easyinput) {

			height: 60px;

		}

		:deep(.uni-easyinput__content.is-input-border) {
			height: 60px;
		}

		:deep(input) {
			font-size: 25px;
			color: #838383
		}

		button {
			color: #fff;
			background-image: linear-gradient(30deg, #1373c6, #47bd00);

			&.active {
				background: linear-gradient(30deg, #ff000b, #f973cb) !important;
			}
		}
	}
</style>